<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\dealer;

use app\api\model\dealer\Referee as RefereeModel;
use app\api\service\User as UserService;
use app\common\model\dealer\User as UserModel;
use cores\exception\BaseException;

/**
 * 分销商用户模型
 * Class User
 * @package app\api\model\dealer
 */
class User extends UserModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'create_time',
        'update_time',
    ];

    /**
     * 资金冻结
     * @param int $dealerId 分销商ID
     * @param string $money 提现资金
     * @return bool
     */
    public static function freezeMoney(int $dealerId, string $money): bool
    {
        // 消减可提现佣金
        static::setDecMoney($dealerId, (float)$money);
        // 增加已冻结佣金
        static::setIncFreezeMoney($dealerId, (float)$money);
        return true;
    }

    /**
     * 累计分销商成员数量
     * @param int $dealerId
     * @param int $level
     * @return mixed
     */
    public static function setMemberInc(int $dealerId, int $level)
    {
        $fields = [1 => 'first_num', 2 => 'second_num', 3 => 'third_num'];
        return (new static)->setInc($dealerId, $fields[$level], 1);
    }

    /**
     * 获取当前用户的推荐人昵称/姓名
     * @return string
     * @throws BaseException
     */
    public static function getRefereeName(): string
    {
        $userId = UserService::getCurrentLoginUserId();
        $refereeId = RefereeModel::getRefereeUserId($userId, 1);
        if ($refereeId > 0 && ($referee = self::detail($refereeId))) {
            return $referee['real_name'] ?: $referee['user']['nick_name'];
        }
        return '平台';
    }

    /**
     * 获取分销商列表 (根据用户ID集)
     * @param array $userIds
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListByUserIds(array $userIds): \think\Collection
    {
        return $this->where('user_id', 'in', $userIds)
            ->where('is_delete', '=', 0)
            ->select();
    }
}